﻿<%@ WebHandler Language="C#" Class="list" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Web.Script.Serialization;
using System.Web.SessionState;
using System.Web.Services;
using System.IO;
using System.Drawing;


public class list : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    private StringBuilder sb = null;
    private StringBuilder sb_1 = null;
    private StringBuilder sb_2 = null;
    private StringBuilder sb_3 = null;
    private StringBuilder sb_4 = null;
    private StringBuilder sb_5 = null;
    public DataSet ds = null;
    public DataTable dt = null;
    private string sqlwhere = "";
    public void ProcessRequest (HttpContext context) {
        string type = PageBase.ext_string(context.Request.Params["type"]);
        switch (type)
        {
            //查询菜单信息
            case "getmenuinfo":
                getmenuinfo(context);
                break;
            //查询类型下拉选项
            case "getselect":
                getselect(context);
                break;
            //查询上传图片信息
            case "getlist":
                getinfo_list(context);
                break;
            //新增
            case "add":
                add(context);
                break;
            //修改
            case "edit":
                edit(context);
                break;
            //删除
            case "delete":
                delete(context);
                break;
            //启用
            case "start":
                start(context);
                break;
            //根据id获取信息
            case "getlist_byid":
                getlist_byid(context);
                break;
            default:
                //getinfo(context);
                break;
        }
    }
    /// <summary>
    /// for循环
    /// </summary>
    /// <param name="yourValue"></param>
    /// <returns></returns>
    public static bool IsRepeat(int[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            for (int j = 0; j < array.Length; j++)
            {
                if (j <= i)
                {
                    continue;
                }
                if (array[i] == array[j])
                {
                    return true;
                }
            }
        }
        return false;
    }
    //查询菜单信息
    public void getmenuinfo(HttpContext context)
    {
        string menuids = PageBase.ext_string(context.Request.Params["menuids"]);    //传递过来菜单id
        string[] strArray = menuids.Split(',');
        //一级菜单
        string sql = @"select id,menuname,menuurl,parentid,xh,rtrim(ltrim(isactive)) as isactive 
                       from dbo.sys_menus where isactive='Y' order by xh";
        sql = string.Format(sql, 0);
        DataTable dt = DBHelper.ExecuteDataTable(sql);

        string checkeds = "true";
        string checkeds_false = "false";
        string spread = "true";
        sb_1 = new StringBuilder();
        sb_1.Append("{\"data\":[");
        int parentid = 0;
        //查找第一个父节点有多少个，即初值为0的父节点  
        DataRow[] rowsP = dt.Select("parentid=" + parentid);
        foreach (DataRow drP in rowsP)
        {
            sb_1.Append("{\"title\":\"" + drP["menuname"].ToString() + "\"");
            sb_1.Append(",\"id\":\"" + drP["id"].ToString() + "\"");
            sb_1.Append(",\"field\":\"" + drP["menuname"].ToString() + "\"");
            //查找该菜单的id是否存在于传递过来的id数组，并且有跳转链接的
            if (strArray.Contains(drP["id"].ToString())&& drP["menuurl"].ToString()!="")
            {
                sb_1.Append(",\"checked\":" + checkeds + "");
            }
            else
            {
                sb_1.Append(",\"checked\":" + checkeds_false + "");
            }
            sb_1.Append(",\"spread\":" + spread + "");
            //二级菜单
            DataRow[] rowsC = dt.Select("parentid=" + drP["id"]);
            if (rowsC.Length > 0)  //如果子节点不为0，则开始拼接子节点的字符串  
            {
                sb_2 = new StringBuilder();
                foreach (DataRow drC in rowsC)
                {
                    sb_2.Append("{\"title\":\"" + drC["menuname"].ToString() + "\"");
                    sb_2.Append(",\"id\":\"" + drC["id"] + "\"");
                    sb_2.Append(",\"field\":\"" + drC["menuname"] + "\"");
                    sb_2.Append(",\"spread\":" + spread + "");
                    if (strArray.Contains(drC["id"].ToString()) && drC["menuurl"].ToString() != "")
                    {
                        sb_2.Append(",\"checked\":" + checkeds + "");
                    }
                    else
                    {
                        sb_2.Append(",\"checked\":" + checkeds_false + "");
                    }
                    sb_2.Append(",\"href\":\"" + drC["menuurl"] + "\"");
                   //三级菜单
                    DataRow[] rowsThree = dt.Select("parentid=" + drC["id"]);
                    //判断是否存在三级菜单
                    if (rowsThree.Length > 0)
                    {
                        sb_3 = new StringBuilder();
                        foreach (DataRow drThree in rowsThree)
                        {
                            sb_3.Append("{\"title\":\"" + drThree["menuname"].ToString() + "\"");
                            sb_3.Append(",\"id\":\"" + drThree["id"] + "\"");
                            sb_3.Append(",\"field\":\"" + drThree["menuname"] + "\"");
                            sb_3.Append(",\"spread\":" + spread + "");
                            if (strArray.Contains(drThree["id"].ToString()) && drThree["menuurl"].ToString() != "")
                            {
                                sb_3.Append(",\"checked\":" + checkeds + "");
                            }
                            else
                            {
                                sb_3.Append(",\"checked\":" + checkeds_false + "");
                            }
                            sb_3.Append(",\"href\":\"" + drThree["menuurl"] + "\"");
                            //四级菜单
                            DataRow[] rowsFour = dt.Select("parentid=" + drThree["id"]);
                            //判断是否存在四级菜单
                            if (rowsFour.Length > 0)
                            {
                                sb_4 = new StringBuilder();
                                foreach (DataRow drFour in rowsFour)
                                {
                                    sb_4.Append("{\"title\":\"" + drFour["menuname"].ToString() + "\"");
                                    sb_4.Append(",\"id\":\"" + drFour["id"] + "\"");
                                    sb_4.Append(",\"field\":\"" + drFour["menuname"] + "\"");
                                    if (strArray.Contains(drFour["id"].ToString()) && drFour["menuurl"].ToString() != "")
                                    {
                                        sb_4.Append(",\"checked\":" + checkeds + "");
                                    }
                                    else
                                    {
                                        sb_4.Append(",\"checked\":" + checkeds_false + "");
                                    }
                                    sb_4.Append(",\"spread\":" + spread + "");
                                    sb_4.Append(",\"href\":\"" + drFour["menuurl"] + "\"},");
                                }
                                string sb4_str = sb_4.ToString();
                                sb4_str = sb4_str.Remove(sb4_str.LastIndexOf(","), 1);
                                sb_3.Append(",\"children\":[" + sb4_str + "]");
                            }
                            sb_3.Append("},");
                        }
                        string sb3_str = sb_3.ToString();
                        sb3_str = sb3_str.Remove(sb3_str.LastIndexOf(","), 1);
                        sb_2.Append(",\"children\":[" + sb3_str + "]");
                    }
                    sb_2.Append("},");
                }
                string sb2_str = sb_2.ToString();
                sb2_str = sb2_str.Remove(sb2_str.LastIndexOf(","), 1);
                sb_1.Append(",\"children\":[" + sb2_str + "]},");
            }
            else
            {
                sb_1.Append("},");
            }
     
        }
        sb_1.Append("]}");

        string sb1_str = sb_1.ToString();
        sb1_str = sb1_str.Remove(sb1_str.LastIndexOf(","), 1);

        context.Response.Write(sb1_str.ToString());
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //查询图标根据id
    public void getlist_byid(HttpContext context)
    {
        string editid = PageBase.ext_string(context.Request.Params["editid"]);
        string sql = @"select id, name, remark, menuids, menunames, ltrim(rtrim(isactive)) isactive, createtime, 
      updatetime from [sys_function] where id={0} ";

        sql = string.Format(sql,editid);
        DataTable dt = DBHelper.ExecuteDataTable(sql);


        sb = new StringBuilder();
        string code = "0";
        string msg = "";
        int count = 0;
        sb.Append("{\"code\":\"" + code + "\",\"count\":" + count + ",\"msg\":\"" + msg + "\",\"data\":[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            sb.Append("{\"id\":\"" + dt.Rows[i]["id"].ToString() + "\"");
            sb.Append(",\"name\":\"" + dt.Rows[i]["name"] + "\"");
            sb.Append(",\"remark\":\"" + dt.Rows[i]["remark"] + "\"");
            sb.Append(",\"menuids\":\"" + dt.Rows[i]["menuids"] + "\"");
            sb.Append(",\"menunames\":\"" + dt.Rows[i]["menunames"] + "\"");
            sb.Append(",\"isactive\":\"" + dt.Rows[i]["isactive"] + "\"");
            sb.Append(",\"updatetime\":\"" + dt.Rows[i]["updatetime"] + "\"");
            sb.Append(",\"createtime\":\"" + dt.Rows[i]["createtime"] + "\"}");
            if (i < dt.Rows.Count - 1)
            {
                sb.Append(",");
            }
        }
        sb.Append("]}");
        context.Response.Write(sb.ToString());
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //启用
    public void start(HttpContext context)
    {
        string getids = PageBase.ext_string(context.Request.Params["getids"]);
        string msg = "";
        bool flag;
        string sqldelete = "update  sys_function set isactive='Y' where id in ({0})";
        sqldelete = string.Format(sqldelete, getids);
        int dtcount= DBHelper.ExecuteNonQuery(sqldelete);
        if (dtcount > 0)
        {
            flag = true;
            msg = "启用成功";
        }
        else
        {
            flag = false;
            msg = "启用失败";

        }
        context.Response.Write("{\"flag\":\"" + flag + "\",\"remsg\":\"" + msg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //删除
    public void delete(HttpContext context)
    {
        string getids = PageBase.ext_string(context.Request.Params["getids"]);
        string msg = "";
        bool flag;
        string sqldelete = "update  sys_function set isactive='N' where id in ({0})";
        sqldelete = string.Format(sqldelete, getids);
        int dtcount= DBHelper.ExecuteNonQuery(sqldelete);
        if (dtcount > 0)
        {
            flag = true;
            msg = "禁用成功";
        }
        else
        {
            flag = false;
            msg = "禁用失败";

        }
        context.Response.Write("{\"flag\":\"" + flag + "\",\"remsg\":\"" + msg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }

    //查询
    public void getinfo_list(HttpContext context)
    {
        //页数1
        int page = PageBase.ext_int(context.Request.Params["page"]);
        //每页条数10
        int limit =PageBase.ext_int(context.Request.Params["limit"]);
        //排序字段
        string field =PageBase.ext_string(context.Request.Params["field"]);
        //排序方式
        string order = PageBase.ext_string(context.Request.Params["order"]);

        string orderby = "createtime";
        string where = @"select  COUNT(*) OVER(PARTITION BY 1) AS TOTAL,id, name, remark, menuids, menunames,
                         ltrim(rtrim(isactive)) isactive, createtime,updatetime  from [sys_function]  where 1=1 ";
        string functionname =PageBase.ext_string(context.Request.Params["functionname"]);
        string sel_isactive =PageBase.ext_string(context.Request.Params["sel_isactive"]);
        //功能名称
        if (!string.IsNullOrEmpty(functionname))
        {
            where += " and name like N'%" + functionname + "%'";
        }
        //是否可用
        if (!string.IsNullOrEmpty(sel_isactive))
        {
            where += " and isactive ='" + sel_isactive + "'";
        }
        if (!string.IsNullOrEmpty(order) && !string.IsNullOrEmpty(field))
        {
            orderby =field + " " + order;
        }
        DataTable dt =  DBHelper.Pagination2(where, limit, page, orderby, "");
        sb = new StringBuilder();
        string code = "0";
        string msg = "";
        int count = 0;
        if(dt.Rows.Count>0)
            count = PageBase.ext_int(dt.Rows[0]["TOTAL"].ToString());
        sb.Append("{\"code\":\"" + code + "\",\"count\":" + count + ",\"msg\":\"" + msg + "\",\"data\":[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            sb.Append("{\"id\":\"" + dt.Rows[i]["id"].ToString() + "\"");
            sb.Append(",\"name\":\"" + dt.Rows[i]["name"] + "\"");
            sb.Append(",\"remark\":\"" + dt.Rows[i]["remark"] + "\"");
            sb.Append(",\"menuids\":\"" + dt.Rows[i]["menuids"] + "\"");
            sb.Append(",\"menunames\":\"" + dt.Rows[i]["menunames"] + "\"");
            sb.Append(",\"isactive\":\"" + dt.Rows[i]["isactive"] + "\"");
            sb.Append(",\"updatetime\":\"" + dt.Rows[i]["updatetime"] + "\"");
            sb.Append(",\"createtime\":\"" + dt.Rows[i]["createtime"] + "\"}");
            if (i < dt.Rows.Count - 1)
            {
                sb.Append(",");
            }
        }
        sb.Append("]}");
        context.Response.Write(sb.ToString());
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //查询类型下拉选项
    public void getselect(HttpContext context)
    {
        string ysdid = PageBase.ext_string(context.Request.Params["ysdid"]);
        string sql = @"select * from [t_type] where ltrim(rtrim(isactive))='Y'";
        DataTable dt = DBHelper.ExecuteDataTable(sql);

        string fsmessage = "";
        sb = new StringBuilder();
        string code = "0";
        string msg = "";
        sb.Append("{\"code\":\"" + code + "\",\"msg\":\"" + msg + "\",\"data\":[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            sb.Append("{\"id\":\"" + dt.Rows[i]["id"].ToString() + "\"");
            sb.Append(",\"typename\":\"" + dt.Rows[i]["typename"] + "\"");
            sb.Append(",\"remark\":\"" + dt.Rows[i]["remark"] + "\"");
            sb.Append(",\"isactive\":\"" + dt.Rows[i]["isactive"] + "\"");
            sb.Append(",\"createtime\":\"" + dt.Rows[i]["createtime"] + "\"}");
            if (i < dt.Rows.Count - 1)
            {
                sb.Append(",");
            }
        }
        sb.Append("]}");
        context.Response.Write(sb.ToString());
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //修改
    public void edit(HttpContext context)
    {
        string msg = "";
        string sqlsave = "";
        bool flag;
        GetDate list = new GetDate();
        using (System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream))
        {
            string s = sr.ReadToEnd();
            list = new JavaScriptSerializer().Deserialize<GetDate>(s);
        }
        string id = Utility.Trim(list.LoadData_type[0].id);
           string functionname = Utility.Trim(list.LoadData_type[0].FUNCTIONNAME);
        string functionremark = Utility.Trim(list.LoadData_type[0].FUNCTIONREMARK);
        string managemenu = Utility.Trim(list.LoadData_type[0].MANAGEMENU);
        string menuid = Utility.Trim(list.LoadData_type[0].MENUID);
        string isactive = Utility.Trim(list.LoadData_type[0].ISACTIVE);
        string isactive_= isactive == "True" ? "Y" : "N";
        string ishave = "select * from sys_function where name='{0}' and ltrim(rtrim(isactive))='Y'";
        ishave = string.Format(ishave, functionname);
        DataTable dtcount= DBHelper.ExecuteDataTable(ishave);
        if (dtcount.Rows.Count > 0 && dtcount.Rows[0]["id"].ToString() != id)
        {
            flag = false;
            msg = "已存在此登录账户，请修改";

        }
        else
        {
            sqlsave = @"update [sys_function] set 
                                   [name]='{0}'
                                  ,[remark]='{1}'
                                  ,[menuids]='{2}'
                                  ,[menunames]='{3}'
                                  ,[isactive]='{4}'
                                  ,[updatetime]='{5}'
                                   where id={6};";
            sqlsave = string.Format(sqlsave,functionname, functionremark,menuid,managemenu,isactive_, DateTime.Now.ToString(), id);
            int zxcount = DBHelper.ExecuteNonQuery(sqlsave);
            if (zxcount > 0)
            {
                flag = true;
                msg = "修改成功";
            }
            else
            {
                flag = false;
                msg = "修改失败，请联系管理员";
            }
        }
        context.Response.Write("{\"flag\":\"" + flag + "\",\"remsg\":\"" + msg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //新增
    public void add(HttpContext context)
    {
        string msg = "";
        string sqlsave = "";
        bool flag;
        GetDate list = new GetDate();
        using (System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream))
        {
            string s = sr.ReadToEnd();
            list = new JavaScriptSerializer().Deserialize<GetDate>(s);
        }
        string functionname = Utility.Trim(list.LoadData_type[0].FUNCTIONNAME);
        string functionremark = Utility.Trim(list.LoadData_type[0].FUNCTIONREMARK);
        string managemenu = Utility.Trim(list.LoadData_type[0].MANAGEMENU);
        string menuid = Utility.Trim(list.LoadData_type[0].MENUID);
        string isactive = Utility.Trim(list.LoadData_type[0].ISACTIVE);
        string isactive_= isactive == "True" ? "Y" : "N";

        string ishave = "select * from sys_function where name='{0}' and ltrim(rtrim(isactive))='Y'";
        ishave = string.Format(ishave, functionname);
        DataTable dtcount= DBHelper.ExecuteDataTable(ishave);
        if (dtcount.Rows.Count > 0)
        {
            flag = false;
            msg = "已存在此功能名称，请修改";
        }
        else
        {
            sqlsave = @"INSERT INTO [sys_function]
                                   ([name]
                                   ,[remark]
                                   ,[menuids]
                                   ,[menunames]
                                   ,[isactive]
                                   ,[createtime]
                                   ,[updatetime]
                                   )
                             VALUES
                                   ('{0}'
                                   ,'{1}'
                                   ,'{2}'
                                   ,'{3}'
                                   ,'{4}'
                                   ,'{5}'
                                   ,'{6}'
                                  );";
            sqlsave = string.Format(sqlsave, functionname, functionremark,menuid,managemenu,isactive_, DateTime.Now.ToString(), DateTime.Now.ToString());
            int zxcount = DBHelper.ExecuteNonQuery(sqlsave);
            if (zxcount > 0)
            {
                flag = true;
                msg = "新增成功";
            }
            else
            {
                flag = false;
                msg = "新增失败，请联系管理员";
            }
        }
        context.Response.Write("{\"flag\":\"" + flag + "\",\"remsg\":\"" + msg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    public class GetDate
    {
        public List<functionmanager> LoadData_type { get; set; }
    }
    public class functionmanager
    {
        //id
        public string id;
        public string ID
        {
            get { return id; }
            set { id = value; }
        }
        public string functionname;
        public string FUNCTIONNAME
        {
            get { return functionname; }
            set { functionname = value; }
        }
        public string functionremark;
        public string FUNCTIONREMARK
        {
            get { return functionremark; }
            set { functionremark = value; }
        }
        public string managemenu;
        public string MANAGEMENU
        {
            get { return managemenu; }
            set { managemenu = value; }
        }
        public string menuid;
        public string MENUID
        {
            get { return menuid; }
            set { menuid = value; }
        }
        public string isactive;
        public string ISACTIVE
        {
            get { return isactive; }
            set { isactive = value; }
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

}